<template>
    <el-container style="height: 100vh;">
        <el-header style="background-color: #f8f9fa; padding: 10px;">
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <h1 style="margin: 0; color: #333;">自动填报系统🤖</h1>
                <el-button type="danger" @click="logout" style="margin-left: 20px;">登出</el-button>
            </div>
        </el-header>
        <el-main style="display: flex; padding: 0;">
            <div class="sidebar" v-loading="uploading || loadingToken">
                <el-form class="form" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px"
                    style="width: 100%;">
                    <el-form-item>
                        <el-icon>
                            <User />
                        </el-icon>
                        <span>当前用户账号: <el-tag>{{ sid }}</el-tag></span>
                    </el-form-item>

                    <el-form-item prop="activatedCode">
                        <el-input prefix-icon="Unlock" v-model="ruleForm.activatedCode" type="text" placeholder="激活码"
                            size="large" class="input-center" />
                    </el-form-item>
                    <el-form-item class="submitBtn">
                        <el-button type="primary" :loading="loading" style="width: 100%;"
                            @click="submitForm('ruleForm')">自动填报</el-button>
                    </el-form-item>
                </el-form>
                <el-upload class="upload-demo" :data="{ token: token, studentId: sid }" drag
                    :before-upload="handleBeforeUpload" action="http://47.238.86.58:5000/upload"
                    :on-success="handleUploadSuccess" :on-progress="handleUploadProgress" :on-error="handleUploadError"
                    :show-file-list="false" multiple="true" accept=".jpg, .jpeg" :disabled="isSubmitting">

                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">拖动或者 <em>点击上传</em></div>
                    <template #tip>
                        <div class="el-upload__tip">上传二维码图片，支持jpg格式
                            <el-tooltip content="将存放班级二维码的压缩包进行解压缩，打开文件夹全选即可" raw-content>
                                <el-icon>
                                    <QuestionFilled />
                                </el-icon>
                            </el-tooltip>
                        </div>
                    </template>
                    <el-progress :percentage="uploadProgress" v-if="uploading"></el-progress> <!-- 显示上传进度 -->
                </el-upload>
            </div>

            <el-aside width="75%" style="padding: 20px; border-left: 1px solid #ebeef5;">
                <h2>日志输出👨‍🔧</h2>
                <span class="progress">
                    <el-progress :percentage="progress" :stroke-width="15" striped  style="margin-top: 20px;"
                        color="green" />
                </span>
                <span style="margin-left: 10px;">当前进度: {{ Math.round(progress) }}%</span> <!-- 显示当前进度 -->

                <el-card v-for="(log, index) in logs" :key="index" class="log-card" shadow="hover">
                    <div>{{ log }}</div>
                </el-card>
            </el-aside>
        </el-main>
    </el-container>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        const validateActive = (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入激活码'));
            } else {
                callback();
            }
        };

        return {
            ruleForm: {
                activatedCode: ''
            },
            rules: {
                activatedCode: [{ validator: validateActive, trigger: 'blur' }]
            },
            loadingToken: true,
            logs: [`⚠️如果已上传的图片为实际班级的人数，班级信息没有改变，不需要再重复上传！`],
            loading: false,
            uploading: false, // 上传状态
            uploadProgress: 0, // 上传进度
            token: sessionStorage.getItem('authToken'),
            sid: sessionStorage.getItem('studentId'),
            totalFiles: 0,
            uploadedFilesCount: 0,
            task: 0,
            isSubmitting: false,
            finished: -1, // 已完成任务数
            progress: 0, // 进度
        };
    },
    created() {
        this.validateToken();
        window.addEventListener('beforeunload', this.handleBeforeUnload);
    },
    beforeDestroy() {
        window.removeEventListener('beforeunload', this.handleBeforeUnload);
    },
    methods: {
        handleBeforeUnload(event) {
            if (this.loading) {
                const message = '您有正在进行的任务，确定要离开吗？';
                event.returnValue = message; // 标准的做法
                return message; // 一些浏览器可能会显示此消息
            }
        },
        validateToken() {
            axios.post('http://47.238.86.58:5000/validate-token', { token: this.token, studentId: this.sid })
                .then(response => {
                    if (response.data.code === 200) {
                        this.loadingToken = false; // 验证成功，结束加载状态
                        this.task = response.data.task;
                        this.logs.splice(1, 0, `🌡️当前已上传的图片数量为：${this.task}`);
                    } else {
                        this.$message.warning('当前登录已过期，请重新登录！');
                        this.logout();
                    }
                })
                .catch(error => {
                    console.error('Token 验证失败:', error);
                    this.loadingToken = false; // 发生错误，结束加载状态
                    this.$message.error('验证 token 时发生错误，请重试！');
                    this.logout();
                });
        },
        logout() {
            this.$confirm('确认要登出吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 清除 sessionStorage 或其他登出逻辑
                sessionStorage.clear();
                this.$message({ message: '已成功登出', type: 'success' });
                // 重定向到登录页面
                this.$router.push('/');
            }).catch(() => {
                this.$message({ type: 'info', message: '已取消登出' });
            });
        },
        handleUploadProgress(event) {
            this.uploading = true; // 开始上传
            if (event.lengthComputable) {
                this.uploadProgress = Math.round((this.uploadedFilesCount / this.totalFiles) * 100); // 更新进度
            }
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.loading = true;
                    this.isSubmitting = true; // 开始填报时禁用上传
                    const formData = {
                        activatedCode: this.ruleForm.activatedCode,
                        token: this.token,
                        studentId: this.sid
                    };

                    axios.post('http://47.238.86.58:5000/start', formData)
                        .then((response) => {
                            const { processId } = response.data;
                            let code = response.data.code;
                            if (code === 401) {
                                this.$message({
                                    message: '身份过期, 请重新登录！',
                                    type: 'error'
                                });
                                sessionStorage.clear();
                                this.$router.push('/');
                                return;
                            }
                            // 开始之前清空日志信息
                            this.progress = 0;
                            this.finished = -1;
                            this.logs = [];
                            this.logs.push(`⚠️开始处理数据，进程ID: ${processId} 请勿中途刷新或退出页面！`);
                            this.$message({ message: '开始处理数据！', type: 'warning' });
                            // 添加计时器
                            const eventSource = new EventSource(`http://47.238.86.58:5000/logs/${processId}`);
                            eventSource.onmessage = (event) => {
                                const data = JSON.parse(event.data);
                                //携带时间
                                this.logs.push(`评价结果：${data.message.msg} ✨ 评价对象学号: ${data.studentId} ✨ 状态码：${data.message.code} 处理时间：${data.time}`);
                                this.finished++; // 增加已完成的任务数
                                // 计算进度
                                this.progress = Math.round((this.finished / this.task) * 100) // 计算进度

                                // 判断数据是否接收完成的条件（例如，通过检查消息的某个字段）
                                if (data.message.code === 'COMPLETED') {
                                    eventSource.close(); // 关闭流
                                    this.loading = false; // 结束加载状态
                                    this.isSubmitting = false; // 结束填报，重新启用上传
                                    // 计算当前日志长度
                                    this.totalFiles = this.logs.length;
                                    // 将最终结果放到列表的第二位
                                    this.logs.splice(1, 0, `🆗数据处理完成，共处理 ${this.task} 条数据, ⏱️任务总用时：${data.totalTime}秒`);
                                    this.logs.splice(1, 0, `💡请检查数据处理的数量与班级的人数是否匹配，共处理 ${this.task} 条数据`);
                                    this.$message({ message: '任务处理完成！', type: 'success' });
                                }

                            };

                            eventSource.onerror = () => {
                                console.error("连接错误");
                                eventSource.close();
                                this.loading = false;
                                this.isSubmitting = false; // 结束填报，重新启用上传

                            };
                        }
                        )
                        .catch((error) => {
                            this.loading = false;
                            this.isSubmitting = false; // 结束填报，重新启用上传

                            this.$message({ message: '登录失败，请检查激活码是否正确！', type: 'error' });
                            console.error(error);
                        });
                } else {
                    console.log('提交失败！');
                    return false;
                }
            });
        },
        handleUploadSuccess(response, file) {
            const code = response.code;
            if (code !== 200) {
                this.$message({
                    message: `文件 ${file.name} 上传失败！${response.message}`,
                    type: 'error'
                });
                this.logs.push(`文件 ${file.name} 上传失败！${response.message}`);
            } else {
                this.logs.push(`文件 ${file.name} 上传成功!`);
            }
            this.uploadedFilesCount++; // 上传成功文件计数
            this.checkUploadCompletion(); // 检查上传是否完成
        },
        handleUploadError(file, response) {
            console.error('上传错误的完整响应:', response);
            const message = (typeof response === 'object' && response.message) ? response.message : '上传失败，未提供错误信息';
            this.logs.push(`文件 ${file.name} 上传失败！${message}`);
            this.uploadedFilesCount++; // 错误也算作上传结束
            this.checkUploadCompletion(); // 检查上传是否完成
        },
        checkUploadCompletion() {
            if (this.uploadedFilesCount === this.totalFiles) {
                this.uploading = false; // 所有文件上传完成
                this.logs.splice(1, 0, `🌡️当前已上传的图片数量为：${this.totalFiles}`);
                // 删除splice(2, 0）
                this.logs.splice(2, 1);
                this.uploadProgress = 0; // 重置进度
            }
        },
        handleBeforeUpload(file) {
            this.totalFiles++; // 每次上传时增加总文件数
            return true; // 允许上传
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        }
    }
}
</script>




<style scoped>
.el-header {
    background-color: #f8f9fa;
    border-bottom: 1px solid #e4e7ed;
    /* 添加底部边框 */
}

:deep(.el-form-item__content) {
    margin-left: 0 !important;
}

.el-main {
    display: flex;
}

.sidebar {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    flex: 1;
    padding: 20px;
    background: white;
}

.el-aside {
    background-color: #ffffff;
}

.log-card {
    margin: 10px 0;
    padding: 10px;
    background-color: #f5f7fa;
    border: 1px solid #e4e7ed;
}

.el-button {
    border-radius: 4px;
    /* 圆角 */
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    /* 阴影效果 */
}
</style>
